<?php

namespace App\Http\Controllers\wx;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Repos\OrderRepo;

use App\Repos\UserCouponRepo;
use App\Repos\UserMoneyLogRepo;
use App\Repos\AdminRepo;
use App\Repos\CartRepo;
use EasyWeChat,Log;
use EasyWeChat\Factory;

use App\Services\WechatTpl;
use App\Models\User;
use App\Models\Order;

use App\Models\OrderProduct;

class PayController extends Controller
{
    public function payNotify()
    {
    	$config = config('wechat.payment.default');    	
    	$app = Factory::payment($config);
    	Log::info('进入回调：');
    	$response = $app->handlePaidNotify(function($message, $fail){
		    // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单

		    $order = OrderRepo::find(['code'=>$message['out_trade_no']]);

		    if (!$order || $order->paid_at) { // 如果订单不存在 或者 订单已经支付过了
		        return true; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
		    }

		   

	if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
		        // 用户是否支付成功
		        if (array_get($message, 'result_code') === 'SUCCESS') {
		        	if(array_get($message,'total_fee')!=$order->total_price) {
		        		Log::info('微信回调订单金额'.array_get($message,'total_fee').'与系统中的订单实际支付金额.'.$order->total_price.'数据不一致');
		        		return false;
		        	}
		            $order->paid_at = array_get($message,'time_end'); // 更新支付时间为当前时间

		           
		            $order->status = '2';	
		           
		            


		// 如果用了满减券 满减券要废掉
		if($order->user_coupon_id) {
		 UserCouponRepo::update(['id'=>$order->user_coupon_id],['is_used'=>1]);
		}

		// 如果使用了余额那么要减掉
		if($order->user_money) {
		    $moneyLog['user_id'] = $order->user_id;
		   
			$moneyLog['type']  	 = 2;
			$moneyLog['money']    = $order->user_money;
			$moneyLog['order_id'] = $order->id;
			//dd($moneyLog);
			UserMoneyLogRepo::create($moneyLog);	
		}  

		$products = OrderProduct::where(['order_id'=>$order->id])->get();
		// 释放购物车
		foreach ($products as $key => $product) {
			$cartWhere['user_id']    =  $order->user_id;				
		
			$cartWhere['product_id'] = $product->product_id;
			CartRepo::release($cartWhere);  	
		}
		    
			


		           

			$order->transaction_id = array_get($message,'transaction_id');

		            

		        // 用户支付失败
		        } elseif (array_get($message, 'result_code') === 'FAIL') {
		            $order->status = '0';
		        }
		} else {
			  	return $fail('通信失败，请稍后再通知我');
		}

		$order->save(); // 保存订单  


		// 推送模板消息
		$msg    = $order->toArray();
		$msg['product_info'] = OrderRepo::productInfo($order->id);
		$msg['openid']       = object_get($order,'user.small_openid');
		WechatTpl::sendTplMsg('paid',$msg); 

		// 推送给管理员
		$admins = AdminRepo::getList();
		foreach ($admins as $k => $admin) {
			if(empty($admin->openid)) continue;
			$msg['nickname'] = object_get($order,'user.nickname');
			$msg['openid'] = $admin->openid;
			$msg['total_amount_txt'] = $order->total_amount_txt;
			$msg['url']    = 'http://jipu.fieldpoint.tech/h5/order-info?order_id='.$order->id;
			WechatTpl::sendAccountMsgTpl('new_to_shop',$msg);
		}
		

		return true; // 返回处理完成
	});

		$response->send(); // return $response;
    }

    /**
     * 红包充值回调
     */
    public function rechargeNotify()
    {
    	$config = config('wechat.payment.shop');    	
    	$app = Factory::payment($config);
    	Log::info('进入回调：');
    	$response = $app->handlePaidNotify(function($message, $fail){
		    // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单

		    $order = ShopRechargeRepo::find(['code'=>$message['out_trade_no']]);

		    if (!$order || $order->paid_at) { // 如果订单不存在 或者 订单已经支付过了
		        return true; // 告诉微信，我已经处理完了，订单没找到，别再通知我了
		    }

		   

		    if ($message['return_code'] === 'SUCCESS') { // return_code 表示通信状态，不代表支付状态
		        // 用户是否支付成功
		        if (array_get($message, 'result_code') === 'SUCCESS') {
		        	if(array_get($message,'total_fee')!=$order->money) {
		        		Log::info('微信回调订单金额'.array_get($message,'total_fee').'与系统中的订单金额.'.$order->money.'数据不一致');
		        		return false;
		        	}
		            $order->paid_at = array_get($message,'time_end'); // 更新支付时间为当前时间
		            $order->status = '2';

		            $order->transaction_id = array_get($message,'transaction_id');

		        // 用户支付失败
		        } elseif (array_get($message, 'result_code') === 'FAIL') {
		            $order->status = '0';
		        }
		    } else {
		        return $fail('通信失败，请稍后再通知我');
		    }

		    $order->save(); // 保存订单

		    // 充值成功 生成红包
		    $data['recharge_id'] = $order->id;
		    $data['shop_id']     = $order->shop_id;
		    $data['money']       = $order->money;		    
		    ShopRechargeRepo::createEnvelop($data);

		   
		    return true; // 返回处理完成
		});

		$response->send(); // return $response;
    }
}
